package com.supermarket.serviceImpl;

import com.supermarket.mapper.fruitMapper;
import com.supermarket.model.Fruit;
import com.supermarket.model.FruitDto;
import com.supermarket.service.SettleAccountsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Component
public class SettleAccountsServiceImpl implements SettleAccountsService {

    @Resource
    private fruitMapper fruitMapper;


    @Override
    public BigDecimal countMoney(List<Fruit> fruitList, boolean flag) {
        BigDecimal countMoney = new BigDecimal(0);

        // 根据数据库中的单价及优惠返回金额
        for (Fruit fruit : fruitList) {
            FruitDto fruitDto = fruitMapper.queryFruitInfo(fruit.getFruitName());
            if (fruitDto != null) {
                if (fruitDto.getFruitDiscount() != null) {
                    countMoney = countMoney.add(fruitDto.getFruitPrice().multiply(fruit.getFruitCount())
                            .multiply(fruitDto.getFruitDiscount()));
                } else {
                    countMoney = countMoney.add(fruitDto.getFruitPrice().multiply(fruit.getFruitCount()));
                }
            }
        }
        // 如果为true进行优惠
        if (flag) {
            // 计算总金额是否满足满100-10的优惠
            return calculateDiscount(countMoney);
        } else {
            return countMoney;
        }
    }

    private BigDecimal calculateDiscount(BigDecimal amount) {
        BigDecimal base = new BigDecimal("100");
        BigDecimal discountPerBase = new BigDecimal("10");
        // 计算满100的次数（向下取整）
        BigDecimal fullTimes = amount.divide(base, 0, RoundingMode.DOWN);
        // 计算总优惠金额
        return amount.subtract(fullTimes.multiply(discountPerBase));
    }
}
